package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import static com.sky.constant.AutoFillConstant.*;

/**
 *自义定的切面类, 用于自动填充公共字段
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    /*
     * 1.切入点
     * 4.切面方法
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}

    //前置通知
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始进行公共字段的自动填充");
        //获取当前拦截的方法的数据库操作类型
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();//获取方法签名
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获取方法上的注解对象
        OperationType operationType = autoFill.value();//获取数据库操作类型
        //获取当前被拦截的方法的参数
        Object[] args = joinPoint.getArgs();
        if (args.length == 0|| args[0] == null){
            return;
        }
        Object object = args[0];
        //设置公共字段的值
        Long currentId = BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();
        if (operationType == OperationType.INSERT){
            //为4个字段赋值
            try {
                object.getClass().getDeclaredMethod(SET_CREATE_TIME, LocalDateTime.class).invoke(object, now);
                object.getClass().getDeclaredMethod(SET_CREATE_USER, Long.class).invoke(object, currentId);
                object.getClass().getDeclaredMethod(SET_UPDATE_TIME, LocalDateTime.class).invoke(object, now);
                object.getClass().getDeclaredMethod(SET_UPDATE_USER, Long.class).invoke(object, currentId);
            } catch (Exception e) {e.printStackTrace();}

        }else if (operationType == OperationType.UPDATE){
            //为2个字段赋值
            try {
                object.getClass().getDeclaredMethod(SET_UPDATE_TIME, LocalDateTime.class).invoke(object, now);
                object.getClass().getDeclaredMethod(SET_UPDATE_USER, Long.class).invoke(object, currentId);
            } catch (Exception e) {e.printStackTrace();}
        }

    }
}

